package org.budo.beetl.resource.localfile;

import java.io.File;
import java.util.Arrays;

import org.beetl.core.GroupTemplate;
import org.beetl.core.Resource;
import org.beetl.core.ResourceLoader;
import org.budo.support.lang.util.FileUtil;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author limingwei
 */
@Getter
@Setter
@Slf4j
public class BudoLocalFileBeetlResourceLoader implements ResourceLoader {
    private String[] root;

    @Override
    public void init(GroupTemplate groupTemplate) {
        log.info("#60 init, this=" + this + ", groupTemplate=" + groupTemplate);
    }

    @Override
    public boolean exist(String key) {
        String[] root = this.getRoot();
        for (String dir : root) {
            Boolean exists = FileUtil.exists(dir, key);
            if (exists) {
                return true;
            }
        }

        // log info
        String message = "#37 view " + key + " not exist at ";
        for (String dir : root) {
            message += "[" + FileUtil.getCanonicalPath(new File(dir, key)) + "]";
        }

        log.info(message);
        return false;
    }

    @Override
    public Resource getResource(String key) {
        String[] root = this.getRoot();

        for (String dir : root) {
            Boolean exists = FileUtil.exists(dir, key);
            if (exists) {
                File file = new File(dir, key);
                Resource resource = new BudoLocalFileBeetlResource(file, key, this);
                resource.setResourceLoader(this);
                return resource;
            }
        }

        throw new RuntimeException("#50 key=" + key + ", root=" + Arrays.toString(root));
    }

    @Override
    public boolean isModified(Resource key) {
        return true;
    }

    @Override
    public void close() {
        throw new RuntimeException();
    }

    @Override
    public String getResourceId(Resource resource, String key) {
        throw new RuntimeException();
    }

    @Override
    public String getInfo() {
        throw new RuntimeException();
    }
}